package com.chnbst.bstyun.controller.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipayNotify;
import com.alipay.util.AlipaySubmit;
import com.alipay.util.IpAdd;
import com.chnbst.bstyun.core.common.BankpayConfig;
import com.chnbst.bstyun.core.common.CreateOrderNum;
import com.chnbst.bstyun.eos.CreateNum;
import com.chnbst.bstyun.eos.Eos;
import com.chnbst.bstyun.model.pojo.Cashflow;
import com.chnbst.bstyun.model.pojo.Deal;
import com.chnbst.bstyun.model.pojo.Goods;
import com.chnbst.bstyun.model.pojo.Order;
import com.chnbst.bstyun.model.pojo.Supplier;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.pojo.Voucher;
import com.chnbst.bstyun.service.CashflowService;
import com.chnbst.bstyun.service.DealService;
import com.chnbst.bstyun.service.GoodsService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.SupplierService;
import com.chnbst.bstyun.service.UserService;
import com.chnbst.bstyun.service.VoucherService;

/**
 * 支付宝即时到账支付相关
 * @author zqh
 * @date 2014年9月26日
 * 
 */

@Controller
@RequestMapping("/alipay")
@SessionAttributes(value={"order","payWayName","EOSresult"})
public class AlipayController {
	
	Logger logger = LoggerFactory.getLogger(AlipayController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private DealService dealService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private VoucherService voucherService;
	@Autowired
	private CashflowService cashflowService;
	@Autowired 
	private Eos eos;
	@Autowired 
	private CreateNum createNum;
	@Autowired
	private BankpayConfig bankpayConfig;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private GoodsService goodsService;
	
	private static final String ROLE_AGENT = "ROLE_AGENT";//代理商
	
	/**
	 * 跳转支付宝处理(充值)
	 * @param request
	 * @return
	 * @throws MalformedURLException
	 * @throws DocumentException
	 * @throws IOException
	 */
	@RequestMapping(value="/doRecharge",method=RequestMethod.GET, produces = "text/html;charset=UTF-8")
	public @ResponseBody String alipayApi(HttpServletRequest request) throws MalformedURLException, DocumentException, IOException{
		String userId =  request.getParameter("userId");
		//充值金额
		String total_fee = request.getParameter("rechargeNum"); 
		String orderNum = CreateOrderNum.getOrderNum(Integer.parseInt(userId));
		String voucherNum = request.getParameter("voucherNum"); 
		//支付类型
		String payment_type = bankpayConfig.getPAYMENT_TYPE();
		//必填，不能修改
		//服务器异步通知页面路径
		String notify_url = bankpayConfig.getNOTIFY_URL();
		//页面跳转同步通知页面路径
		String return_url = bankpayConfig.getRETURN_URL();
		//卖家支付宝帐户
		String seller_email = bankpayConfig.getSELLER_EMAIL();
		//商户订单号
		String out_trade_no = orderNum;
		//订单名称
		String subject = bankpayConfig.getSUBJECT();
		//订单描述
		String body = bankpayConfig.getBODY();
		//商品展示地址
		String show_url = bankpayConfig.getSHOW_URL();
		//防钓鱼时间戳
		String anti_phishing_key = AlipaySubmit.query_timestamp();
		//客户端的IP地址
		String exter_invoke_ip = IpAdd.getIpAddr(request);
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "create_direct_pay_by_user");
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", payment_type);
		sParaTemp.put("notify_url", notify_url);
		sParaTemp.put("return_url", return_url);
		sParaTemp.put("seller_email", seller_email);
		sParaTemp.put("out_trade_no", out_trade_no);
		sParaTemp.put("subject", subject);
		sParaTemp.put("total_fee", total_fee);
		sParaTemp.put("body", body);
		sParaTemp.put("show_url", show_url);
		sParaTemp.put("anti_phishing_key", anti_phishing_key);
		sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
		sParaTemp.put("extra_common_param",userId+","+voucherNum); //公用回传参数===用户ID，代金券编号voucherNum========================================
		//建立请求
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
		return sHtmlText;
	}
	
	/**
	 * 支付宝即时支付异步返回处理（充值）
	 * 充值成功后只保存交易流水记录
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/notify_url")
	public void notifyUrl(HttpServletRequest request,HttpServletResponse response) throws IOException{
		//获取支付宝POST过来反馈信息
		PrintWriter out = response.getWriter();
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		String common_param = request.getParameter("extra_common_param");
		String commons[] = common_param.split(",");
		String userId = commons[0];
		String voucherNum = commons[1];
		
		//商户订单号
		String out_trade_no = request.getParameter("out_trade_no");
		//支付宝交易号
		String trade_no = request.getParameter("trade_no");
		//交易状态
		String trade_status = request.getParameter("trade_status");
		// 交易金额
		String total_fee = request.getParameter("total_fee");
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		if(AlipayNotify.verify(params)){//验证成功
			if(trade_status.equals("TRADE_FINISHED")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					
				//注意：
				//该种交易状态只在两种情况下出现
				//1、开通了普通即时到账，买家付款成功后。
				//2、开通了高级即时到账，从该笔交易成功时间算起，过了签约时的可退款时限（如：三个月以内可退款、一年以内可退款等）后。
			} else if (trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					
				//注意：
				//该种交易状态只在一种情况下出现——开通了高级即时到账，买家付款成功后。
			}

			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
			out.println("success");	//请不要修改或删除
			
			// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓充值保存交易流水相关（wangxl）↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
			Double voucherMoney = 0.00;
			if(!"0".equals(voucherNum)) {
				//使用代金券充值部分
				Voucher voucher = voucherService.selectByVoucherNum(voucherNum);
				voucher.setState(1);
				voucherService.updateVoucher(voucher);
				voucherMoney = voucher.getVoucherMoney();
				
				User _userMain = userService.selectUserInfoByUserId(Integer.parseInt(userId));
				_userMain.setAccountMoney(_userMain.getAccountMoney() + voucherMoney);
				userService.updateUserByKey(_userMain);
				
				Cashflow cashflow = new Cashflow();
				cashflow.setCashflowNum(createNum.createCashflowNum("1"));
				cashflow.setCreateTime(new Date());
				cashflow.setDealType(1);
				cashflow.setDisburseMoney(0.00);
				cashflow.setIncomeMoney(voucherMoney);
				cashflow.setOrderId(0);
				cashflow.setPayWayId(2);
				cashflow.setThenAccount(_userMain.getAccountMoney());
				cashflow.setUserId(_userMain.getUserId());
				cashflow.setIsCancel(0);
				cashflowService.insertCashflow(cashflow);
			}
			
			//使用第三方充值部分
			User userMain = userService.selectUserInfoByUserId(Integer.parseInt(userId));
			userMain.setAccountMoney(userMain.getAccountMoney() + Double.parseDouble(total_fee));
			boolean b = userService.updateUserByKey(userMain);
			if(b){
				//=============================收支明细增加======================================
				
				Cashflow cashflow = new Cashflow();
				cashflow.setCashflowNum(createNum.createCashflowNum("2"));
				cashflow.setCreateTime(new Date());
				cashflow.setDealType(1);
				cashflow.setDisburseMoney(0.00);
				cashflow.setIncomeMoney(Double.parseDouble(total_fee));
				cashflow.setOrderId(0);//充值不存在订单ID
				cashflow.setPayWayId(1);
				cashflow.setThenAccount(userMain.getAccountMoney());
				cashflow.setUserId(Integer.parseInt(userId));
				cashflow.setIsCancel(0);
				cashflowService.insertCashflow(cashflow);
				//============================================================================
			}
			// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑充值保存交易流水相关↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
		}else{//验证失败
			out.println("fail");
		}
	}
	
	/**
	 * 购买支付跳转到支付宝支付页面
	 * @param request
	 * @return
	 * @throws MalformedURLException
	 * @throws DocumentException
	 * @throws IOException
	 */
	@RequestMapping(value="/doPay",method=RequestMethod.GET, produces = "text/html;charset=UTF-8")
	public @ResponseBody String AlipayForPay(HttpServletRequest request) throws MalformedURLException, DocumentException, IOException{
		String userId = request.getParameter("userId");
		String proMealName = request.getParameter("proMealName");// 产品或套餐名称
		String orderId = request.getParameter("orderId");// 订单号，主键
		String accountMoney = request.getParameter("payByAccountMoney");// 使用用户账户余额支付部分钱数
		String voucher = request.getParameter("voucher");// 代金券编号
		
		double voucherMoney = 0.00;
		if(!"0".equals(voucher)) {
			voucherMoney = voucherService.selectVoucherByVoucherNum(voucher).getVoucherMoney();
		}
		Order order = orderService.selectOrderByOrderId(Integer.valueOf(orderId));
		
		double payByAccountMoney = Double.valueOf(accountMoney);
		if(payByAccountMoney < 0) {
			payByAccountMoney = 0.00;
		}
		
		
		/**
		 * 根据用户的roleId 来查询是否为代理商，如果是代理商，查询出优惠折扣计算
		 */
		DecimalFormat df = new DecimalFormat("#0.00");
		String mealPrivilege = "1";
		String proPrivilege = "1";
		
		User loginUser = userService.selectUserInfoByUserId(Integer.valueOf(userId));
		if(loginUser.getRoleId().equals(ROLE_AGENT) && loginUser.getSupplierId() != null){
			Supplier supplierInfo = supplierService.selectSupplierBySupplierId(loginUser.getSupplierId());
			if(supplierInfo.getIsValid() == 1){
				mealPrivilege = df.format(supplierInfo.getMealPrivilege());
				proPrivilege = df.format(supplierInfo.getProPrivilege());
			}
		}
		double orderMoney = order.getOrderMoney();
		
		Goods goods = goodsService.selectGoodsVoByGoodsId(order.getGoodsId());
		if("0".equals(goods.getGoodsRalateGoods())){
			orderMoney = orderMoney * Double.valueOf(mealPrivilege);
		}else{
			orderMoney = orderMoney * Double.valueOf(proPrivilege);
		}
		
		double temp = orderMoney-voucherMoney-payByAccountMoney;
		DecimalFormat decimalFormat = new DecimalFormat("#.00");
		
		//订单支付金额
		String total_fee = decimalFormat.format(temp);
		logger.info("total_fee:"+total_fee);
		//商户订单号（订单编号）
		String out_trade_no = request.getParameter("orderNum");
		//支付类型
		String payment_type = bankpayConfig.getPAYMENT_TYPE();
		//服务器异步通知页面路径
		String notify_url = bankpayConfig.getPAY_NOTIFY_URL();
		//页面跳转同步通知页面路径
		String return_url = bankpayConfig.getPAY_RETURN_URL();
		//卖家支付宝帐户
		String seller_email = bankpayConfig.getSELLER_EMAIL();
		//订单名称
		String subject = proMealName;
		//订单描述
		String body = proMealName;
		//商品展示地址
		String show_url = bankpayConfig.getSHOW_URL();
		//防钓鱼时间戳
		String anti_phishing_key = AlipaySubmit.query_timestamp();
		//客户端的IP地址
		String exter_invoke_ip = IpAdd.getIpAddr(request);
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "create_direct_pay_by_user");
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", payment_type);
		sParaTemp.put("notify_url", notify_url);
		sParaTemp.put("return_url", return_url);
		sParaTemp.put("seller_email", seller_email);
		sParaTemp.put("out_trade_no", out_trade_no);
		sParaTemp.put("subject", subject);
		sParaTemp.put("total_fee", total_fee);
		sParaTemp.put("body", body);
		sParaTemp.put("show_url", show_url);
		sParaTemp.put("anti_phishing_key", anti_phishing_key);
		sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
		sParaTemp.put("extra_common_param",
				  userId+","+orderId+","+payByAccountMoney+","+voucher); //公用回传参数(用户id,订单id，产品id，账户余额支付钱数，代金券编号)

		//建立请求
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
		return sHtmlText;
	}
	
	/**
	 * 服务器异步通知页面跳转（支付）
	 * 购买支付成功后保存交易流水记录，同时修改订单状态
	 * @param request
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/pay_notify_url")
	public void alipayNotifyUrl(HttpServletRequest request,HttpServletResponse response) throws Exception{
		//获取支付宝POST过来反馈信息
		PrintWriter out = response.getWriter();
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		String common_param = request.getParameter("extra_common_param");
		String commons[] = common_param.split(",");
		String userId = commons[0];
		String orderId = commons[1];
		String payByAccountMoney = commons[2];
		String voucher = commons[3];
		
		//商户订单号
		String out_trade_no = request.getParameter("out_trade_no");
		//支付宝交易号
		String trade_no = request.getParameter("trade_no");
		//交易状态
		String trade_status = request.getParameter("trade_status");
		// 交易金额
		String total_fee = request.getParameter("total_fee");
		String subject = request.getParameter("subject");
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		if(AlipayNotify.verify(params)){//验证成功
			if(trade_status.equals("TRADE_FINISHED")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					
				//注意：
				//该种交易状态只在两种情况下出现
				//1、开通了普通即时到账，买家付款成功后。
				//2、开通了高级即时到账，从该笔交易成功时间算起，过了签约时的可退款时限（如：三个月以内可退款、一年以内可退款等）后。
			} else if (trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					
				//注意：
				//该种交易状态只在一种情况下出现——开通了高级即时到账，买家付款成功后。
			}

			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
			// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓保存交易流水相关（wangxl）↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
			
			
			// 根据userId获取user所有信息
			User userInfo = userService.selectUserInfoByUserId(Integer.parseInt(userId));
			Double accountMoney = 0.0;
			Double invoiceMoney = 0.0;
			if(!"0.00".equals(payByAccountMoney)){
				accountMoney = userInfo.getAccountMoney()-Double.parseDouble(payByAccountMoney);
				invoiceMoney = userInfo.getInvoiceMoney() + Double.parseDouble(payByAccountMoney);
				//账户余额更新
				userInfo.setAccountMoney(accountMoney);
				userInfo.setInvoiceMoney(invoiceMoney);
				userService.updateUserByKey(userInfo);
			}
			//修改代金券状态
			if(!"0".equals(voucher)){
				Voucher v = voucherService.selectVoucherByVoucherNum(voucher);
				v.setState(1);
				voucherService.updateVoucher(v);
			}
			
			//订单状态修改
			Order order = orderService.selectOrderByOrderId(Integer.parseInt(orderId));
			Goods goods = goodsService.selectGoodsVoByGoodsId(order.getGoodsId());
			/*if(order.getBuyType() == 0) {
				
				if("0".equals(goods.getGoodsRalateGoods())){
					if(SignUtil.isNotEmpty(String.valueOf(order.getNewProId()))) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("mealId", order.getMealId());
						map.put("userId", order.getUserId());
						map.put("sortField", "pay_time");
						map.put("sortOrder", "desc");
						Order entity = orderService.selectOrderByMealIdAndProductId(map);
						order.setProIds(entity.getProIds()+"|"+order.getNewProId());
					}
				}
			}*/
			
			//新加
			order.setPayByOther(Double.parseDouble(total_fee));
			order.setPayByAccount(Double.parseDouble(payByAccountMoney));
			order.setPayMoney(Double.parseDouble(total_fee)+Double.parseDouble(payByAccountMoney));
			
			/**
			 * 根据用户的roleId 来查询是否为代理商，如果是代理商，查询出优惠折扣计算
			 */
			DecimalFormat df = new DecimalFormat("#0.00");
			String mealPrivilege = "1";
			String proPrivilege = "1";
			
			User loginUser = userService.selectUserInfoByUserId(Integer.valueOf(userId));
			if(loginUser.getRoleId().equals(ROLE_AGENT) && loginUser.getSupplierId() != null){
				Supplier supplierInfo = supplierService.selectSupplierBySupplierId(loginUser.getSupplierId());
				if(supplierInfo.getIsValid() == 1){
					mealPrivilege = df.format(1-supplierInfo.getMealPrivilege());
					proPrivilege = df.format(1-supplierInfo.getProPrivilege());
				}
			}
			double discount = order.getOrderMoney();
			
			if("0".equals(goods.getGoodsRalateGoods())){
				discount = discount * Double.valueOf(mealPrivilege);
			}else{
				discount = discount * Double.valueOf(proPrivilege);
			}
			order.setDiscount(discount);
			order.setOrderState(1);
			order.setPayTime(new Date());
			order.setPayWayId(1);
			orderService.updateOrderByOrderId(order);
			
			//激活新用户
			User user = userService.selectUserInfoByUserId(order.getUserId());
			user.setIsLive("1");
			userService.updateUserByKey(user);
			
			// 保存交易流水
			Deal deal = new Deal();
			deal.setDealDate(new Date());
			deal.setDealName(subject);
			deal.setDealNum(out_trade_no);
			deal.setDealState("2");
			deal.setDisburseMoney(Double.parseDouble(total_fee));
			deal.setIncomeMoney(0.0);
			deal.setPayWayId(1);
			deal.setParentId(userInfo.getUserId());
			deal.setUserId(order.getUserId());
			deal.setIsCancel(0);
			dealService.insertDeal(deal);
			
			//=============================收支明细增加======================================
			
			//充值记录
			Cashflow cashflow = new Cashflow();
			cashflow.setCashflowNum(createNum.createCashflowNum("2"));
			cashflow.setCreateTime(new Date());
			cashflow.setDealType(1);
			cashflow.setDisburseMoney(0.00);
			cashflow.setIncomeMoney(Double.parseDouble(total_fee));
			cashflow.setOrderId(Integer.parseInt(orderId));
			cashflow.setPayWayId(1);
			cashflow.setThenAccount(userInfo.getAccountMoney() + Double.parseDouble(total_fee));
			cashflow.setUserId(Integer.parseInt(userId));
			cashflow.setIsCancel(0);
			cashflowService.insertCashflow(cashflow);
			
			//消费记录
			Cashflow cashflow1 = new Cashflow();
			cashflow1.setCashflowNum(createNum.createCashflowNum("1"));
			cashflow1.setCreateTime(new Date());
			cashflow1.setDealType(2);
			cashflow1.setDisburseMoney(Double.parseDouble(total_fee));
			cashflow1.setIncomeMoney(0.00);
			cashflow1.setOrderId(Integer.parseInt(orderId));
			cashflow1.setPayWayId(1);
			cashflow1.setThenAccount(userInfo.getAccountMoney());
			cashflow1.setUserId(Integer.parseInt(userId));
			cashflow.setIsCancel(0);
			cashflowService.insertCashflow(cashflow1);
			
			//============================================================================
			
			
			out.println("success");	//请不要修改或删除
			// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑保存交易流水相关↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
		}else{//验证失败
			out.println("fail");
		}
	}
	
//	/**
//	 * @return 成功页面(购买)
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "/successOrder", method = RequestMethod.GET)
//	public ModelAndView successOrder(HttpServletRequest request,ModelMap model) throws Exception {
//		String out_trade_no = request.getParameter("out_trade_no");
//		String total_fee = request.getParameter("total_fee");
//		Order order = new Order();
//		order.setOrderNum(out_trade_no);
//		order.setOrderMoney(Double.parseDouble(total_fee));
//		ModelAndView modelAndView = new ModelAndView();
//		modelAndView.addObject("order", order);
//		modelAndView.addObject("payWayName", "支付宝支付");
//		model.addAttribute("order", order);
//		model.addAttribute("payWayName", "支付宝支付");
//		// 用户id
//		String common_param = request.getParameter("extra_common_param");
//		String commons[] = common_param.split(",");
//		String userId = commons[0];
//		String productId = commons[2];
//		User userMain = userService.selectUserInfoByUserId(Integer.parseInt(userId));
//		request.getSession().setAttribute("userInfo", userMain);
//		
//		String result = "";
//		if(Integer.valueOf(productId) == 0) {
//			//========================普元同步开始<套餐>====================================//
//			if(order.getMealId() != 2) {
//				result = eos.sendMeal(order.getOrderId());
//			}
//			//========================普元同步结束<套餐>====================================//
//		}else{
//			//========================普元同步开始<产品>====================================//
//			result = eos.sendProduct(order.getOrderId());
//			//========================普元同步结束<产品>====================================//
//		}
//		// 如果普元返回result值为OK，则证明同步成功，否则提示用户联系客服
//		if("ok".equals(request)){
//			System.out.println("成功！");
//		}else{
//			System.out.println("失败，请联系客服！");
//		}
//		modelAndView.setViewName("redirect:/alipay/buy/success");
//		return modelAndView;
//	}
	
	@RequestMapping("/buy/success")
	public String getOrderSuccess(){
		return "buy/success-order";
	}
	
	@RequestMapping("/uporder/success")
	public String getUpOrderSuccess(){
		return "users/myservice/uporders_success";
	}
	
	/**
	 * @return 成功页面(购买)
	 * @throws Exception
	 */
	@RequestMapping(value = "/successOrder", method = RequestMethod.GET)
	public ModelAndView OrderSuccess(HttpServletRequest request,ModelMap model) throws Exception{
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号
		String out_trade_no = request.getParameter("out_trade_no");
		String total_fee = request.getParameter("total_fee");
		//支付宝交易号
		String trade_no = request.getParameter("trade_no");
		//交易状态
		String trade_status = request.getParameter("trade_status");
		ModelAndView modelAndView = new ModelAndView();
		if(AlipayNotify.verify(params)){
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
			}
			Order order = new Order();
			order.setOrderNum(out_trade_no);
			order.setOrderMoney(Double.parseDouble(total_fee));
			modelAndView.addObject("order", order);
			modelAndView.addObject("payWayName", "支付宝支付");
			model.addAttribute("order", order);
			model.addAttribute("payWayName", "支付宝支付");
			// 用户id
			String common_param = request.getParameter("extra_common_param");
			String commons[] = common_param.split(",");
			String userId = commons[0];
			String orderId = commons[1];
			User userMain = userService.selectUserInfoByUserId(Integer.parseInt(userId));
			request.getSession().setAttribute("userInfo", userMain);
			Order orderInfo = orderService.selectOrderByOrderId(Integer.parseInt(orderId));
			
			Goods goods = goodsService.selectGoodsVoByGoodsId(orderInfo.getGoodsId());
			String EOSresult = "";
			if(orderInfo.getBuyType() == 0) {
				
				if("0".equals(goods.getGoodsRalateGoods())){
					//========================普元同步开始<套餐>====================================//
					System.out.println(orderInfo.getMealId()+"==================");
					EOSresult = eos.sendMeal(orderInfo);
					//========================普元同步结束<套餐>====================================//
				}else{
					//========================普元同步开始<产品>====================================//
					EOSresult = eos.sendProduct(orderInfo);
					//========================普元同步结束<产品>====================================//
				}
			}else {
				EOSresult = eos.sendProOrMeal(orderInfo);
			}
			
			if("ok".equals(EOSresult)) {
				orderInfo.setIsDredge(1);
				orderService.updateOrderByOrderId(orderInfo);
			}
			
			modelAndView.addObject("EOSresult", EOSresult);
			model.addAttribute("EOSresult", EOSresult);
			if(orderInfo.getBuyType() == 0) {
				modelAndView.setViewName("redirect:/alipay/buy/success");
			}else {
				modelAndView.setViewName("redirect:/alipay/uporder/success");
			}
			return modelAndView;
		}
		return null;
	}
	
	/**
	 * @return 成功页面（充值)
	 * @throws Exception
	 */
	@RequestMapping(value = "/successRecharge", method = RequestMethod.GET)
	public ModelAndView successRecharge(HttpServletRequest request,ModelMap model) throws Exception {
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号
		String out_trade_no = request.getParameter("out_trade_no");
		String total_fee = request.getParameter("total_fee");
		//支付宝交易号
		String trade_no = request.getParameter("trade_no");
		//交易状态
		String trade_status = request.getParameter("trade_status");
		ModelAndView modelAndView = new ModelAndView();
		if(AlipayNotify.verify(params)){
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
			}
			Order order = new Order();
			order.setOrderNum(out_trade_no);
			order.setOrderMoney(Double.parseDouble(total_fee));
			modelAndView.addObject("order", order);
			modelAndView.addObject("payWayName", "支付宝支付");
			model.addAttribute("order", order);
			model.addAttribute("payWayName", "支付宝支付");
			// 用户id
			String common_param = request.getParameter("extra_common_param");
			String commons[] = common_param.split(",");
			String userId = commons[0];
			String voucherNum = commons[1];
			
			User userMain = userService.selectUserInfoByUserId(Integer.parseInt(userId));
			request.getSession().setAttribute("userInfo", userMain);
			modelAndView.setViewName("redirect:/alipay/recharge/success");
			return modelAndView;
		}
		return null;
	}
	
	@RequestMapping("/recharge/success")
	public String getRechargeSuccess(){
		return "users/finance_manage/my_account/recharge_success";
	}
	
}

